package com.geektime.hello.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geektime.hello.entity.User;
import com.geektime.hello.service.IUserService;
import com.geektime.hello.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author pzy
 * @since 2020-06-17
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping
    public Object getUserList() throws JsonProcessingException {
        Object usersCache = redisUtils.get("users");
        if (usersCache == null) {
            List<User> users = userService.list();
            ObjectMapper mapper = new ObjectMapper();
            String usersJson = mapper.writeValueAsString(users);
            redisUtils.set("users", usersJson);
            usersCache = usersJson;
        }
        //20s后缓存失效，下次请求从数据库中获取
        redisUtils.expire("users", 20);
        return usersCache;
    }

    @PostMapping()
    public String saveUser(@RequestBody String reqParams) {
        log.info("reqParams=" + reqParams);
        return reqParams;
    }
}
